package com.dd.cloud.user.service.paynotice.promode.notice;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dd.cloud.common.constants.IntegralConstants;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.user.entity.doctor.DoctorEquity;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.entity.product.Product;
import com.dd.cloud.user.entity.product.ProductBuyRecord;
import com.dd.cloud.user.entity.product.ProductGiveRule;
import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.mq.RabbitSend;
import com.dd.cloud.user.res.doctor.DoctorEquityDetailRes;
import com.dd.cloud.user.service.doctor.IDoctorEquityService;
import com.dd.cloud.user.service.log.ILogErrorService;
import com.dd.cloud.user.service.paynotice.promode.NoticeService;
import com.dd.cloud.user.service.paynotice.promode.NoticeType;
import com.dd.cloud.user.service.product.IProductBuyRecordService;
import com.dd.cloud.user.service.product.IProductGiveRuleService;
import com.dd.cloud.user.service.product.IProductService;
import com.zk.pay.constants.CS;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 支付包月产品回调
 */
@NoticeType(source = CS.NOTICE_SOURCE.PAY, proType = CS.NOTICE_CHANNEL.MONTH)
@Slf4j
public class ProductPayNoticeService implements NoticeService {
    @Autowired
    private ILogErrorService logErrorService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductBuyRecordService productBuyRecordService;
    @Autowired
    private IDoctorEquityService doctorEquityService;

    @Autowired
    private RabbitSend rabbitSend;

    @Autowired
    private IProductGiveRuleService productGiveRuleService;


    /**
     * 支付回调处理逻辑 预约咨询问诊的回调, 修改业务数据状态
     *
     * @param request
     * @param orderPay 订单对象
     * @param flowNo   流水编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void notice(HttpServletRequest request, OrderPay orderPay, String flowNo) {
        try {
            String serverNo = orderPay.getServerNo();
            Integer id = Integer.valueOf(serverNo);
            ProductBuyRecord pbr = productBuyRecordService.getById(id);
            if (pbr == null) {
                logErrorService.presBackLog("包月产品回调抛异常", "包月产品回调抛异常-产品购买记录为null", "serverNo=" + orderPay.getServerNo());
                return;
            }
            Product product = productService.getById(pbr.getProductId());
            if (product == null) {
                logErrorService.presBackLog("包月产品回调抛异常", "包月产品回调抛异常-产品记录为null", "serverNo=" + orderPay.getServerNo());
                return;
            }
            pbr.setOrderNo(orderPay.getOrderNo());
            pbr.setPayDate(LocalDateTime.now());
            pbr.setStartDate(LocalDateTime.now());
            DoctorEquityDetailRes equityDetail = doctorEquityService.queryDoctorEquityDetail(pbr.getDoctorId());
            if (equityDetail != null && equityDetail.getId() != null) {
                if (equityDetail.getExpirDate() == null) {
                    pbr.setExpirDate(LocalDate.now().atTime(23, 59, 59).plusMonths(pbr.getMonth()));
                } else {
                    pbr.setExpirDate(equityDetail.getExpirDate().plusMonths(pbr.getMonth()));
                }
                DoctorEquity de = new DoctorEquity();
                de.setId(equityDetail.getId());
                de.setExpirDate(pbr.getExpirDate());
                if (product.getPower() == 1) {
                    de.setFirstMonth(1);
                }
                long day = Duration.between(LocalDate.now().atTime(23, 59, 59), pbr.getExpirDate()).toDays();
                de.setAccumulateDay((int) (de.getAccumulateDay() + day));
                de.setAccumulateFee(de.getAccumulateFee() + product.getDiscountPrice());
                doctorEquityService.updateById(de);
            } else {
                pbr.setExpirDate(LocalDate.now().atTime(23, 59, 59).plusMonths(pbr.getMonth()));
                DoctorEquity de = new DoctorEquity();
                de.setDoctorId(pbr.getDoctorId());
                de.setExpirDate(pbr.getExpirDate());
                if (product.getPower() == 1) {
                    de.setFirstMonth(1);
                }
                long day = Duration.between(LocalDate.now().atTime(23, 59, 59), pbr.getExpirDate()).toDays();
                de.setAccumulateDay((int) day);
                de.setAccumulateFee(product.getDiscountPrice());
                de.setCreateDate(LocalDateTime.now());
                de.setType(1);
                doctorEquityService.save(de);
            }
            pbr.setStatus(1);
            productBuyRecordService.updateById(pbr);
            if (pbr.getSpType() == 2) {
                String params = IntegralConstants.IntegralType.TWENTY_FOUR + "-" + pbr.getDoctorId();
                log.info("月会员,参数为{}", params);
                rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params);
            } else if (pbr.getSpType() == 3) {
                String params = IntegralConstants.IntegralType.TWENTY_FIVE + "-" + pbr.getDoctorId();
                log.info("季会员,参数为{}", params);
                rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params);
            } else if (pbr.getSpType() == 4) {
                String params = IntegralConstants.IntegralType.TWENTY_SIX + "-" + pbr.getDoctorId();
                log.info("年会员,参数为{}", params);
                rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params);
            }
//            saveDoctorEquity(pbr.getDoctorId());
        } catch (Exception e) {
            e.printStackTrace();
            logErrorService.presBackLog("包月产品回调抛异常", "包月产品回调抛异常", "serverNo=" + orderPay.getServerNo());
        }


    }


}
